package com.yangkunhong.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = {"/UserServlet136/*","/UserLogServlet136/*"})
public class LoginFilter implements Filter {
    private static List<String> onNeedLoginURL = Arrays.asList(
            "/UserServlet136/login","/UserServlet136/reg",
            "/test"
    );
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("INIT");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("执行过滤");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(request.getSession().getAttribute("USER_INFO") == null && needLogin(request)){
            response.sendRedirect(request.getContextPath()+"/UserServlet136/login");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    private boolean needLogin(HttpServletRequest request) {
        if(onNeedLoginURL.contains(request.getContextPath()+request.getRequestURI())){
            return false;
        }
        return true;

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
